<template>
  <div class="home-container">
    <div class="menu" :style="{ width: menuWidth + 'px' }">
      <FileVersion ref="fileVersionRef" @file-select="handleFileSelect" />
    </div>
    <div class="resizer" @mousedown="initResize"></div>
    <div class="content" ref="contentRef">
      <Loading :loading="loading" />
      
      <template v-if="!loading">
        <template v-if="currentView === 'list'">
          <div 
            v-for="(project, index) in projects"
            :key="project.id"
            :ref="el => { if (el) cardRefs[project.id] = el }"
          >
            <ImageCard
              :title="project.name"
              :description="getProjectFileInfo(project.id)"
              :images="getProjectImages(project.id)"
              :active="currentProject?.id === project.id"
              :project-id="project.id"
              @version-click="handleVersionClick(index)"
              @dependency-click="handleDependencyClick(index)"
            />
          </div>
        </template>
        
        <template v-else-if="currentView === 'graph'">
          <el-button @click="handleBackToList">返结果视图</el-button>
          <GraphCard
            v-if="currentDependencyData"
            :key="`graph-${Date.now()}`"
            :title="currentProject?.name || ''"
            :data="currentDependencyData"
            :projects="projects"
          />
        </template>
      </template>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, onBeforeUpdate } from 'vue'
import { storeToRefs } from 'pinia'
import FileVersion from '@/components/FileVersion.vue'
import ImageCard from '@/components/ImageCard.vue'
import GraphCard from '@/components/GraphCard.vue'
import Loading from '@/components/common/Loading.vue'
import { useProjectStore } from '@/stores/projectStore'
import { useChartStore } from '@/stores/chartStore'

const store = useProjectStore()
const chartStore = useChartStore()

const {
  projects,
  loading,
  currentView,
  currentProject,
  currentDependencyData
} = storeToRefs(store)

const fileVersionRef = ref(null)
const menuWidth = ref(300) // 初始宽度

const cardRefs = ref({})

// 在更新前清除旧的 refs
onBeforeUpdate(() => {
  cardRefs.value = {}
})

const handleVersionClick = (index) => {
  const project = projects.value[index];
  fileVersionRef.value?.openProject(project.id);

  const currentFileId = store.getProjectCurrentFile(project.id);
  store.setActiveFileId(currentFileId);
};

const handleDependencyClick = async (index) => {
  const project = projects.value[index]
  
  // 在当前项目中查找选中的文件
  let currentFile = project.files.find(file => file.id === store.activeFileId)

  // 如果当前项目中没有选中的文件，则使用该项目的最新版本文件
  if (!currentFile) {
    currentFile = [...project.files]
      .sort((a, b) => parseFloat(b.version) - parseFloat(a.version))[0]
  }

  store.setActiveFileId(currentFile.id)
  fileVersionRef.value?.openProject(project.id)
  store.setCurrentView('graph')
  // 使用当前选中文件的名称获取依赖
  await store.fetchDependencies(currentFile.name)
}

const handleBackToList = () => {
  store.setCurrentView('list')
  store.resetDependencyData()
}

const initResize = (e) => {
  window.addEventListener('mousemove', resize)
  window.addEventListener('mouseup', stopResize)
}

const resize = (e) => {
  menuWidth.value = e.clientX
}

const stopResize = () => {
  window.removeEventListener('mousemove', resize)
  window.removeEventListener('mouseup', stopResize)
}

// 获取项目当前显示的文件信息
const getProjectFileInfo = (projectId) => {
  const project = projects.value.find(p => p.id === projectId);
  if (!project) return '';

  const currentFileId = store.getProjectCurrentFile(projectId);
  const currentFile = currentFileId 
    ? project.files.find(f => f.id === currentFileId)
    : project.files[0];  // 如果没有选中的文件，显示第一个文件

  return currentFile ? `${currentFile.name} (v${currentFile.version}) ${currentFile.description}` : '';
};

// 获取项目当前显示的图片
const getProjectImages = (projectId) => {
  const project = projects.value.find(p => p.id === projectId);
  if (!project) return [];

  const currentFileId = store.getProjectCurrentFile(projectId);
  const currentFile = currentFileId 
    ? project.files.find(f => f.id === currentFileId)
    : project.files[0];

  return currentFile ? currentFile.images : [];
};

// 处理文件选择
const handleFileSelect = async (fileId, action) => {
  const project = projects.value.find(p => 
    p.files.some(f => f.id === fileId)
  );

  if (!project) return;

  // 更新当前选中的文件ID
  store.setActiveFileId(fileId);

  switch (action) {
    case 'scroll':
      // 列表视图：滚动到对应卡片
      if (cardRefs.value[project.id]) {
        cardRefs.value[project.id].scrollIntoView({ 
          behavior: 'smooth',
          block: 'start'
        });
      }
      break;

    case 'graph':
      // 图表视图：更新依赖关系图
      const currentFile = project.files.find(file => file.id === fileId);
      if (currentFile) {
        // 图表已经在 FileVersion 中更新，这里只需要确保视图同步
        chartStore.updateChart(store.currentDependencyData, projects.value);
      }
      break;
  }
};

onMounted(async () => {
  await store.fetchProjects()
})
</script>

<style scoped>
.home-container {
  display: flex;
  height: 100vh;
  width: 100%;
  position: fixed;
  left: 0;
  top: 0;
  overflow: hidden;
}

.menu {
  background-color: #f5f5f5;
  overflow-y: auto;
  height: 100%;
  flex-shrink: 0;
  &::-webkit-scrollbar {
    width: 6px;
  }
  &::-webkit-scrollbar-thumb {
    background-color: #ccc;
    border-radius: 3px;
  }
}

.resizer {
  width: 5px;
  cursor: col-resize;
  background-color: #ddd;
  height: 100%;
  flex-shrink: 0;
}

.content {
  flex: 1;
  padding: 12px;
  overflow-y: auto;
  background-color: #fff;
  min-width: 0;
  height: 100%;
  &::-webkit-scrollbar {
    width: 6px;
  }
  &::-webkit-scrollbar-thumb {
    background-color: #ccc;
    border-radius: 3px;
  }
}
</style>